using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Script.Serialization;

namespace MvcApp.Controllers
{
    public class ScheduleTemplatesController: BaseApiController
    {
        private readonly IScheduleTemplatesService _service;
        private readonly IScheduleTemplateItemsService _itemsService;
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        //todo get from settings
        TimeSpan endDay = new TimeSpan(20, 0, 0);


        public ScheduleTemplatesController(IScheduleTemplatesService service, IScheduleTemplateItemsService itemsService)
        {
            _service = service;
            _itemsService = itemsService;
        }

        [ActionName("GetByProvider")]
        public List<ScheduleTemplate> GetByProvider(Guid providerId)
        {
            var user = System.Web.Security.Membership.GetUser(User.Identity.Name);
            if (user != null && user.ProviderUserKey != null)
            {
                var filterObj = new ScheduleTemplateFilter {ProviderId = providerId};
                
                
                return _service.Get(filterObj).OrderByDescending(o=>o.CreatedOn).ToList();
            }
            return null;
        }

        public HttpResponseMessage Post([FromBody]ScheduleTemplate value)
        {
            var user = System.Web.Security.Membership.GetUser(User.Identity.Name);
            if (user != null && user.ProviderUserKey != null)
            {
                Guid userId = (Guid)user.ProviderUserKey;
                if (_service.Save(userId, value)) return Request.CreateResponse(HttpStatusCode.OK, value);
                return Request.CreateResponse(HttpStatusCode.OK, "Saved");
            }
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Please sign in!");

        }

        // DELETE api/<controller>/5
        [HttpDelete]
        public void Delete(string id)
        {
            var ids = serializer.Deserialize<List<Guid>>(id);
            if (_service.Delete(ids)) Request.CreateResponse(HttpStatusCode.OK);

        }

        [ActionName("GetByScheduleTemplate")]
        public List<ScheduleTemplateItem> GetByTemplate(Guid scheduleTemplateId)
        {
            var user = System.Web.Security.Membership.GetUser(User.Identity.Name);
            if (user != null && user.ProviderUserKey != null)
            {
                var scheduleTemplate = _service.GetById(scheduleTemplateId);
                
                var filterObj = new ScheduleTemplateItemFilter { ScheduleTemplateId = scheduleTemplateId};
                var scheduleTemplateItems=_itemsService.Get(filterObj).OrderBy(o => o.DayNumber).ThenBy(o=>o.StartTime).ToList();

                var emptyTemplateItems = new List<ScheduleTemplateItem>();

                if (scheduleTemplate.Start1.HasValue) FillScheduleTemplateItems(scheduleTemplateId, scheduleTemplate.TimeForOnePerson, scheduleTemplate.Start1.Value, endDay, emptyTemplateItems, 1);
                if (scheduleTemplate.Start2.HasValue) FillScheduleTemplateItems(scheduleTemplateId, scheduleTemplate.TimeForOnePerson, scheduleTemplate.Start2.Value, endDay, emptyTemplateItems, 2);
                if (scheduleTemplate.Start3.HasValue) FillScheduleTemplateItems(scheduleTemplateId, scheduleTemplate.TimeForOnePerson, scheduleTemplate.Start3.Value, endDay, emptyTemplateItems, 3);
                if (scheduleTemplate.Start4.HasValue) FillScheduleTemplateItems(scheduleTemplateId, scheduleTemplate.TimeForOnePerson, scheduleTemplate.Start4.Value, endDay, emptyTemplateItems, 4);
                if (scheduleTemplate.Start5.HasValue) FillScheduleTemplateItems(scheduleTemplateId, scheduleTemplate.TimeForOnePerson, scheduleTemplate.Start5.Value, endDay, emptyTemplateItems, 5);
                if (scheduleTemplate.Start6.HasValue) FillScheduleTemplateItems(scheduleTemplateId, scheduleTemplate.TimeForOnePerson, scheduleTemplate.Start6.Value, endDay, emptyTemplateItems, 6);
                if (scheduleTemplate.Start7.HasValue) FillScheduleTemplateItems(scheduleTemplateId, scheduleTemplate.TimeForOnePerson, scheduleTemplate.Start7.Value, endDay, emptyTemplateItems, 7);

                foreach (var item in scheduleTemplateItems)
                {
                    var index =
                        emptyTemplateItems.FindIndex(o => o.StartTime == item.StartTime && o.DayNumber == item.DayNumber);
                    if (index >= 0) emptyTemplateItems[index] = item;
                }

                return emptyTemplateItems.OrderBy(o => o.DayNumber).ThenBy(o => o.StartTime).ToList();
            }
            return null;
        }

        private void FillScheduleTemplateItems(Guid scheduleTemplateId, int timeForOnePerson, TimeSpan start, TimeSpan endDay, List<ScheduleTemplateItem> emptyTemplateItems, int dayNumber)
        {
            while (start < endDay)
            {
                emptyTemplateItems.Add(new ScheduleTemplateItem
                    {
                        Id = Guid.NewGuid(),
                        ScheduleTemplateId = scheduleTemplateId,
                        DayNumber = dayNumber,
                        Length = timeForOnePerson,
                        StartTime = start
                    });
                start = start.Add(new TimeSpan(0, timeForOnePerson, 0));
            }
        }
    }

    
}